package com.kevin.action;

import java.awt.image.BufferedImage;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.imageio.ImageIO;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.mvc.annotation.AdaptBy;
import org.nutz.mvc.annotation.At;
import org.nutz.mvc.annotation.Fail;
import org.nutz.mvc.annotation.Ok;
import org.nutz.mvc.annotation.Param;
import org.nutz.mvc.upload.UploadAdaptor;

import com.kevin.common.DwzoutMapUtil;
import com.kevin.service.UploadService;
import com.kevin.util.Arith;
import com.kevin.util.ImageCut;
import com.kevin.util.SysParamsToolkit;
import com.kevin.validate.Errors;


/**
 * 
  * @ClassName: UploadAction 
  * @Description: 上传下载模块
  * @author 吕凯
  * @date 2012-10-29 上午10:24:34 
  *
 */
@IocBean
@At("/upload")
public class UploadAction {

	@Inject
	private UploadService uploadService;
	
	
	/**
	 * 
	  * @方法名  uploadfile 
	  * @功能描述  上传文件
	  * @编码人   吕凯
	  * @编码时间  2012-9-24 下午01:56:13 
	  * @输入参数   @param f
	  * @输入参数   @param context
	  * @输入参数   @param es
	  * @输入参数   @return
	  * @输入参数   @throws Exception 
	  * @返回值  Map
	 */
	@At
	@AdaptBy(type = UploadAdaptor.class, args = { "ioc:myUpload"})
	@Ok("json")
	@Fail("json") 
	public Map<String,Object> uploadfile(@Param("file_upload") File f, ServletContext context,Errors es) {	
		System.out.println(f);
		Map<String,Object> returnMap =  new HashMap<String, Object>();
		returnMap.put("error", "123");
		try {
			returnMap = uploadService.uploadFile(f, "articleinfo",context.getRealPath("/"));
			returnMap.remove("error");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally{
			System.out.println("map=="+returnMap);
		}
		return returnMap;			
	}
	/**
	 * 
	  * @方法名  uploadimg 
	  * @功能描述  上传头像
	  * @author   吕凯  
	  * @param f
	  * @param context
	  * @param es
	  * @return 
	  * @return  Map<String,Object> 
	  * @编码时间 2012-11-1 下午08:14:56
	 */
	@At
	@AdaptBy(type = UploadAdaptor.class)
	@Ok("json")
	@Fail("json") 
	public Map<String,Object> uploadimg(@Param("file_upload") File f, HttpServletRequest req,ServletContext context,Errors es) {	
		System.out.println(f);
		Map<String,Object> returnMap =  new HashMap<String, Object>();
		returnMap.put("error", "123");
		try {
			//检查图片大小
			BufferedImage src = ImageIO.read(f); // 读入文件	
			String IMGROOT = "/uploads/";
			/**图片上传的相对路径*/
			String imgWebAppPath = f.getAbsolutePath();
			/**图片后缀*/
			String imgFileExt = null;
			String imgUploadPath = null;
			//图片初始化高度与宽度
			String width = null;
			String height = null;
			
			int imgWidth = 0;
			int imgHeight = 0;
			//指定图片宽度和高度 最大
			width = req.getParameter("width");
			if(null == width){
				width = "500";
			}
			height= req.getParameter("height");	
			if(null == height){
				height = "400";
			}
			
			imgWidth = Integer.parseInt(width);
			imgHeight = Integer.parseInt(height);
			
			
			//文件个数
			int fileCounts =  1;	
			
			for (int i = 0; i <fileCounts; i++) {
				
				
				int imgSrcWidth = src.getWidth(); // 得到源图宽					
				int imgSrcHeight = src.getHeight(); // 得到源图长
				//等比例压缩
				//重新指定大小
				if(imgSrcWidth> imgWidth){
					imgSrcHeight = Math.round((float)Arith.div(imgSrcHeight, Arith.div(imgSrcWidth, imgWidth)));
					imgSrcWidth = imgWidth;
				}//宽超出比例
				if(imgSrcHeight > imgHeight){
					imgSrcWidth = Math.round((float)Arith.div(imgSrcWidth, Arith.div(imgSrcHeight, imgHeight)));
					imgSrcHeight = imgHeight;
				}//高超出比例
				imgWidth = imgSrcWidth > imgWidth ? imgWidth : imgSrcWidth;
				imgHeight = imgSrcHeight > imgHeight ? imgHeight : imgSrcHeight;
				
				//按照图片的设置大小生成
				ImageCut.scale(imgWebAppPath, imgWebAppPath,imgWidth,imgHeight);
				if(f.exists()){						
					System.out.println("创建"+imgWidth+"*"+imgHeight+"图片成功");
				}
				
			}
			
			returnMap = uploadService.uploadFile(f, "uploads",context.getRealPath("/"));
			returnMap.remove("error");
			imgUploadPath = IMGROOT + returnMap.get("sysfilename")+"";
			imgFileExt = returnMap.get("atttype")+"";
			
			String path = context.getContextPath()+"/jsp/back/user/imgcrop2.jsp?tag=0&oldImgPath="+imgUploadPath+"&imgFileExt="+imgFileExt+"&imgRoot="+IMGROOT+"&width="+imgWidth+"&height="+imgHeight;
			
			returnMap =  DwzoutMapUtil.getDwzoutMap(DwzoutMapUtil.SUCCESS, "图片上传成功，请进行裁剪！", "", "", "forward", path, "");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally{
			System.out.println("map=="+returnMap);
		}
		return returnMap;			
	}
	
	/**
	 * 
	  * @方法名  uploadimg 
	  * @功能描述  上传头像
	  * @author   吕凯  
	  * @param f
	  * @param context
	  * @param es
	  * @return 
	  * @return  Map<String,Object> 
	  * @编码时间 2012-11-1 下午08:14:56
	 */
	@At
	@Ok("json")
	@Fail("json") 
	public Map<String,Object> imgcut(HttpServletRequest req,ServletContext context,Errors es) {	
		Map<String,Object> returnMap =  new HashMap<String, Object>();
		System.out.println("x: " + req.getParameter("x") + "," + req.getParameter("y") + "," + req.getParameter("w") + "," + req.getParameter("h"));

		// 用户经过剪辑后的图片的大小
		Integer x = Integer.parseInt(req.getParameter("x"));
		Integer y = Integer.parseInt(req.getParameter("y"));
		Integer w = Integer.parseInt(req.getParameter("w"));
		Integer h = Integer.parseInt(req.getParameter("h"));
		
		//获取原显示图片路径
		String oldImgPath = req.getParameter("oldImgPath");
		//图片后缀
		String imgFileExt = req.getParameter("imgFileExt");
		String imgRoot =  req.getParameter("imgRoot");
		
		//WEB应用程序根路径
		String webAppPath = context.getRealPath("/");
		
		/**图片名称:以当前日期*/
		SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddhhmmss");
		String imgFileId = formatter.format(new Date());
		String imgName =  imgRoot + imgFileId + System.currentTimeMillis() + "." + imgFileExt;			
		//组装图片真实名称
		String createImgPath = webAppPath + imgName;
		
		//之前上传的图片路径
		webAppPath += oldImgPath;
		
		System.out.println("原图片路径: " + webAppPath + ",新图片路径: " + createImgPath);
		
		//进行剪切图片操作
		ImageCut.abscut(webAppPath, createImgPath, x,y,w, h);
		
		 File f = new File(createImgPath);								
		 if(f.exists()){						
			 System.out.println("剪切图片大小: "+w+"*"+h+"图片成功!");
		 }	
		 
		String path = context.getContextPath()+"/jsp/back/user/imgcrop.jsp?tag=1&oldImgPath="+oldImgPath+"&imgFileExt="+imgFileExt+"&imgRoot="+imgRoot + "&imgName="+imgName+"&height=" + h + "&width=" + w;
		System.out.println("imgCrop: " + path);
		returnMap =  DwzoutMapUtil.getDwzoutMap(DwzoutMapUtil.SUCCESS, "裁剪成功！", "", "", "forward", path, "");
		return returnMap;			
	}
	/**
	 * 
	  * @方法名  deletefile 
	  * @功能描述  删除上传文件
	  * @编码人   吕凯
	  * @编码时间  2012-9-24 下午01:55:56 
	  * @输入参数   @param filename
	  * @输入参数   @param number
	  * @输入参数   @param context
	  * @输入参数   @param es
	  * @输入参数   @return
	  * @输入参数   @throws Exception
	  * @返回值  Map
	 */
	@At
	@Ok("json")
	public void deletefile(String filename,String number, ServletContext context,Errors es) throws Exception{
		System.out.println("delete"+filename+"========="+number);
		uploadService.deleteFile(filename, "articleinfo",context.getRealPath("/"));
	}
	/**
	 * 
	  * @方法名  getArticleatts 
	  * @功能描述  获取附件
	  * @编码人   吕凯
	  * @编码时间  2012-10-19 下午02:52:21 
	  * @输入参数   @param filename
	  * @输入参数   @param number
	  * @输入参数   @param context
	  * @输入参数   @param es
	  * @输入参数   @throws Exception 
	  * @返回值  void
	 */
	@At
	@Ok("raw")
	public void getArticleatts(HttpServletRequest request,HttpServletResponse response, ServletContext context,Errors es) throws Exception{
		Integer type = null;
		try {
			type = Integer.parseInt(request.getParameter("t"));
		} catch (Exception e) {}
		if(type != null){
			String filename = request.getParameter("file");
			String dirPath = SysParamsToolkit.getProperty("file"+type);
			File file = new File(context.getRealPath("/") +"/"+dirPath+"/"+ filename);
			response.reset(); //非常重要
			response.setContentType("application/force-download");
			response.setHeader("Content-Disposition","attachment;filename=" + java.net.URLEncoder.encode(filename,"UTF-8"));
			response.addHeader("Content-Length", ""+file.length());
			OutputStream out = response.getOutputStream();
			
			BufferedInputStream br = new BufferedInputStream(new FileInputStream(file));
			byte[] buf = new byte[1024];
			int len = 0; 
			while((len = br.read(buf))>0)
			out.write(buf,0,len);
			br.close(); 
			out.flush();
			out.close();
		}
	}
	
}
